<template>
  <el-dialog v-if="dialogVisible" v-model="dialogVisible" title="计算项目计算公式向导" width="75%" :close-on-click-modal="false" :before-close="handleClose" top="5px" destroy-on-close>
    <div>
      <el-input type="textarea" disabled v-model="description"></el-input>
    </div>
    <div class="margin-top-xs">
      <el-input id="formulaTextRefId" ref="formulaTextRef" type="textarea" v-model="formula" @blur="formulaTextRefBlur"></el-input>
    </div>
    <Splitpanes style="height: 45vh" class="margin-top-xs">
      <Pane :size="40">
        <vxe-toolbar perfect>
          <template #buttons>
            <span class="text-bold">双击选中</span>
          </template>
          <template #tools>
            <vxe-input v-model="searchValue" placeholder="关键字查询"></vxe-input>
            <el-button class="button-blue margin-left-xs">查询</el-button>
          </template>
        </vxe-toolbar>
        <div style="height: calc(45vh - 30px)">
          <vxe-table ref="itemTable" class="mytable-scrollbar" height="auto" resizable border="inner" show-header-overflow show-overflow align="center" :row-config="{ isCurrent: true, isHover: true }" :data="dataList" @cell-dblclick="cellDbClick">
            <vxe-column type="seq" width="26px"></vxe-column>
            <vxe-column field="itemNo" title="项目代号" width="106px">
              <template #default="{ row }">
                <span>{{ row.itemNo }}</span>
              </template>
            </vxe-column>
            <vxe-column field="itemNa" title="项目名称" width="126px">
              <template #default="{ row }">
                <span>{{ row.itemNa }}</span>
              </template>
            </vxe-column>
            <vxe-column field="itemClass" title="项目归类" width="100px">
              <template #default="{ row }">
                <span>{{ row.itemClass }}</span>
              </template>
            </vxe-column>
            <vxe-column field="instrClass" title="仪器大类" width="100px"></vxe-column>
            <vxe-column field="itemEnCode" title="英文缩写" width="100px"></vxe-column>
            <vxe-column field="unit" title="单位" width="80px"></vxe-column>
            <vxe-column field="inputcode" title="输入码" width="86px"></vxe-column>
            <vxe-column field="enable" title="启用/禁用" width="90px">
              <template #default="{ row }">
                <span :class="(row.enable==='0'||row.enable===0)?'text-grey':'text-green'">{{ (row.enable==='0'||row.enable===0)?'已禁用':'已启用' }}</span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane :size="30">
        <div class="grid col-4">
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('+')">+</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('-')">-</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('*')">*</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('/')">/</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('(')">(</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick(')')">)</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick(`[SEX]='1'`)">性别男</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick(`[SEX]='2'`)">性别女</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick(`[AGE]`)">年龄</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">申请科室</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">申请病区</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">诊断名称</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">送检医院</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">条码号</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">病人来源</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">样本类型</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">检验者</el-button>
          </div>
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item">审核者</el-button>
          </div>
        </div>
        <el-divider content-position="left">说明</el-divider>
        <div class="padding-tb padding-lr-xs">
          <p>1、计算公式中不可包括其它计算项目，若有需要，一律转化为最原始的计算公式</p>
          <p>2、所有项目代号必须使用“[”和“]”括起来</p>
          <p>3、表达式可以为一个常数或空字符串</p>
        </div>
        <!-- <el-divider></el-divider> -->
      </Pane>
      <Pane :size="30">
        <el-divider content-position="left">
          <span class="text-orange">其他可用函数(双击使用)</span></el-divider>
        <el-scrollbar style="width: 100%; height: calc(45vh - 50px)">
          <div class="padding-tb padding-lr-xs">
            <div class="cu-list menu">
              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('SUBSTR()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">1</span> 字符串截取
                  </div>
                  <div>SUBSTR(string, start_position, length)</div>
                  <div class="text-df">string:被截取的字符串;</div>
                  <div class="text-df">start_position:截取开始未知,正数从左往右截取;</div>
                  <div class="text-df">length:截取长度;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('MOD()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">2</span> 取余数
                  </div>
                  <div>MOD(dividend, divisor)</div>
                  <div class="text-df">dividend:被除数;</div>
                  <div class="text-df">divisor:除数;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('ABS()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">3</span> 取绝对值
                  </div>
                  <div>ABS(x)</div>
                  <div class="text-df">x:被取绝对值数值;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('ROUND()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">4</span> 四舍五入
                  </div>
                  <div>ROUND(number, precision)</div>
                  <div class="text-df">number:要进行四舍五入的值;</div>
                  <div class="text-df">precision:要保留的小数位数,可选, 默认为0;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('LN()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">5</span> 取自然对数
                  </div>
                  <div>LN(number)</div>
                  <div class="text-df">number:要计算自然对数的值;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('LOG()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">6</span>
                    以10为底的对数
                  </div>
                  <div>LOG(number, base)</div>
                  <div class="text-df">number:要计算自然对数的值;</div>
                  <div class="text-df">base:是对数的底数,可选,默认为10;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('SQRT()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">7</span> 平方根
                  </div>
                  <div>SQRT(number)</div>
                  <div class="text-df">number:要计算平方根的值;</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('TAN()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">8</span> 正切
                  </div>
                  <div>TAN(angle)</div>
                  <div class="text-df">angle:要计算正切值的角度(以弧度为单位);</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('SIN()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">9</span> 正弦
                  </div>
                  <div>SIN(angle)</div>
                  <div class="text-df">angle:要计算正弦值的角度(以弧度为单位);</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('COS()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">10</span> 余弦
                  </div>
                  <div>COS(angle)</div>
                  <div class="text-df">angle:要计算余弦值的角度(以弧度为单位);</div>
                </div>
              </div>

              <div class="cu-item">
                <div class="content">
                  <div class="text-bold cursor-pointer" @dblclick="actionBtnClick('EXP()')">
                    <span class="bg-green light padding-lr-xs margin-right-xs">11</span>
                    计算e的n次方
                  </div>
                  <div>EXP(n)</div>
                  <div class="text-df">n:指数值;</div>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </Pane>
    </Splitpanes>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="reset">重置</el-button>
        <el-button @click="toggleShowHide">取消</el-button>
        <el-button @click="confirmFormula" class="button-blue">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance, watch, defineProps } from 'vue';
import { IsEmpty } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';

let props = defineProps({
  type: { type: String, default: '' }, //计算公式类别，结果计算公式，结果1计算公式   结果2计算公式   结果3计算公式
  description: { type: String, default: '' },/*公式描述*/
  formula: { type: String, default: '' },/*公式值*/
  rptGroup: { type: String, default: '' }/**报告单元Id */
}) as any;
let showLoading = ref(false);
let searchValue = ref('');

const itemTable = ref(null);
const formulaTextRef = ref(null);

defineExpose({ toggleShowHide });
let { proxy }: any = getCurrentInstance();
let dialogVisible = ref(false);
let description = ref('');/*公式描述*/
let formula = ref('');/*公式*/
let rowConfig = ref({ isCurrent: true, isHover: true });
let dataList = reactive([]);
let selectRows = ref([]);
let rptGroup = ref('');/**报告单元主键 */
/**
 * 监听公式变化
 */
watch(() => props.formula, (n, v) => {
  if (!IsEmpty(n)) {
    formula.value = n;
  } else {
    formula.value = '';
  }
}, { immediate: true, deep: true });
/**
 * 监听描述变化
 */
watch(() => props.description, (n, v) => {
  if (!IsEmpty(n)) {
    description.value = n;
  } else {
    description.value = '';
  }
}, { immediate: true, deep: true });

/**
 * 查询所有项目
 */
function findItemDicts() {
  if (IsEmpty(rptGroup.value)) {
    VxeMessage('请选择报告单元', VxeNotifyType.warning);
    return;
  }
  dataList.length = 0;
  showLoading.value = true;
  const url = '/lis/lab/item/findLabItemDictList';
  const data = { searchValue: searchValue.value, rptGroup: IsEmpty(rptGroup.value) ? null : rptGroup.value };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      //dataList.push(...res.data);
      dataList.push(...res.data);
      if (dataList.length > 0) {
        rowClick({
          row: dataList[0]
        });
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
      showLoading.value = false;
    });
}
/**
 * 表格点击当前行
 */
const rowClick = ({ row }) => {
  if (itemTable.value) {
    itemTable.value.setCurrentRow(row);
  }
};
/**
 * 单元格双击事件
 */
function cellDbClick({ row }) {
  description.value += `[${row.itemNa}]`;
  insertText(`[${row.itemNo}]`);
}

/**
 * 在光标位置插入数据计算
 */
function insertText(text) {
  let textarea = formulaTextRef.value?.$refs.textarea as any;
  let startPos = textarea.selectionStart; // 获取光标起始位置
  let endPos = textarea.selectionEnd; // 获取光标结束位置
  let value = IsEmpty(formula.value) ? '' : formula.value;
  let newValue =
    value.substring(0, startPos) +
    text +
    value.substring(endPos, value.length);
  formula.value = newValue;

  //#region  匹配描述
  calcDescription();
  //#endregion

  textarea.focus(); // 将焦点设置回文本框
  proxy.$nextTick(() => {
    textarea.setSelectionRange(startPos + text.length, startPos + text.length); // 设置光标位置
  });
}
/**
 * 公式输入框失去焦点
 */
function formulaTextRefBlur() {
  calcDescription();
}
/**
 * 公式输入框失去焦点
 */
function calcDescription() {
  const str = formula.value;
  const regex = /\[(.*?)\]/g; // 使用非贪婪模式匹配所有中括号内的内容
  let match;
  let newStr = formula.value;
  while ((match = regex.exec(str)) !== null) {
    const extractedString = match[1]; // 获取捕获组中的内容
    const am = dataList.filter(p => p.itemNo === extractedString);
    if (am && am.length > 0) {
      newStr = newStr.replace(`[${extractedString}]`, `[${am[0].itemNa}]`);
    }
  }
  description.value = newStr;
}
/**
 * 加 减 乘 除括号 功能按钮
 */
function actionBtnClick(e) {
  description.value += `${e}`;
  //formula.value += `${e}`;
  insertText(`${e}`);
}
/**
 * 切换窗体显示/隐藏
 */
function toggleShowHide(obj: any) {
  dialogVisible.value = !dialogVisible.value;
  if (dialogVisible.value) {
    rptGroup.value = obj.rptGroup;
    findItemDicts();
  }
}
/**
 * 重置公式
 */
function reset() {
  formula.value = '';
  description.value = '';
}
/**
 * 关闭
 */
function handleClose() {
  dialogVisible.value = false;
}
/**
 * 确定公式
 */
function confirmFormula() {
  proxy.$emit('confirmFormula', {
    type: props.type,
    description: description.value,
    formula: formula.value
  });
  toggleShowHide();
}
</script>
<style lang="scss" scoped>
.cursor-pointer {
  cursor: pointer;
}
.cursor-pointer:hover {
  text-decoration: underline;
  color: #ff9900;
}
</style>
